<script lang="ts" setup>
import { computed } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VBEN_DOC_URL, VBEN_GITHUB_URL } from '@vben/constants';
import { BookOpenText, CircleHelp, MdiGithub, LockKeyhole } from '@vben/icons';
import {
  BasicLayout,
  LockScreen,
  UserDropdown,
} from '@vben/layouts';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { openWindow } from '@vben/utils';

import { $t } from '#/locales';
import { useAuthStore } from '#/store';
import ChangePasswordModalComp from '#/views/auth/user/change-password-modal.vue';

const userStore = useUserStore();
const authStore = useAuthStore();
const accessStore = useAccessStore();

// 使用 useVbenModal 创建修改密码模态窗口
const [ChangePasswordModal, changePasswordModalApi] = useVbenModal({
  connectedComponent: ChangePasswordModalComp,
});

const menus = computed(() => [
  {
    handler: () => {
      openWindow(VBEN_DOC_URL, {
        target: '_blank',
      });
    },
    icon: BookOpenText,
    text: $t('widgets.document'),
  },
  {
    handler: () => {
      openWindow(VBEN_GITHUB_URL, {
        target: '_blank',
      });
    },
    icon: MdiGithub,
    text: 'Gitee',
  },
  {
    handler: () => {
      openWindow(`${VBEN_GITHUB_URL}/issues`, {
        target: '_blank',
      });
    },
    icon: CircleHelp,
    text: $t('widgets.qa'),
  },
  {
    handler: () => {
      handleChangePassword();
    },
    icon: LockKeyhole,
    text: $t('user.changePassword.title'),
  },
]);

const avatar = computed(() => {
  return userStore.userInfo?.avatar ?? preferences.app.defaultAvatar;
});

async function handleLogout() {
  await authStore.logout(false);
}

// 处理修改密码
function handleChangePassword() {
  console.log('用户信息调试:', userStore.userInfo);

  // 从后端mock数据看，字段名是id而不是userId
  const userId = userStore.userInfo?.id;

  if (userId) {
    console.log('找到用户ID:', userId);
    changePasswordModalApi.setData({
      userId: userId, // 直接使用，不转换类型
    });
    changePasswordModalApi.open();
  } else {
    console.error('用户信息不可用，userInfo:', userStore.userInfo);
  }
}

</script>

<template>
  <BasicLayout @clear-preferences-and-logout="handleLogout">
    <template #user-dropdown>
      <UserDropdown
        :avatar
        :menus
        :text="$t(`${userStore.userInfo?.realName}`)"
        :description="userStore.userInfo?.email"
        tag-text="Pro"
        @logout="handleLogout"
      />
    </template>
    <template #extra>
      <!-- 修改密码模态窗口 -->
      <ChangePasswordModal />
    </template>
    <template #lock-screen>
      <LockScreen :avatar @to-login="handleLogout" />
    </template>
  </BasicLayout>
</template>
